<?php

class ProductController extends Controller
{
  public function actionIndex()
  {
    $categoryID   = isset($_GET['catID']) ? $_GET['catID'] : '';
    $categoryName = '';
    if ($categoryID != '') {
      $category = $this->loadCategoryModel($categoryID);
      if (!empty($category)) {
        $categoryName = Category::model()->getName($category->id);
      }
    }
    $search = isset($_POST['search']) ? $_POST['search'] : '';
    
    $products   = Product::model()->getProducts($categoryID, '', $search);
    if (!empty($products)) {
      foreach ($products as $key => $product) {
        $image = Product::model()->getProductFile($product['id'], 250, 240);
        if ($image == 'no_image.jpg') {
          unset($products[$key]);
        }
      }
    }
    $this->render('index', array(
      'products' => $products, 'categoryName' => $categoryName
    ));
  }
  
  public function actionDetail($id)
  {
    $model    = $this->loadModel($id);
    $criteria = Product::model()->search()->criteria;
    $criteria->addCondition("t.id = $model->id");
    $product  = Product::model()->find($criteria);
    $category = Category::model()->getName($model->categoryID);
    
    $related_products = Product::model()->getProducts(md5($model->categoryID), $model->id);
    if (!empty($related_products)) {
      foreach ($related_products as $key => $related_product) {
        $image = Product::model()->getProductFile($related_product['id'], 250, 240);
        if ($image == 'no_image.jpg') {
          unset($related_products[$key]);
        }
      }
    }
    
    $this->render('detail', array(
      'product' => $product,
      'category' => $category,
      'related_products' => $related_products
    ));
  }
  public function loadCategoryModel($catID)
  {
    $model = Category::model()->find(array(
      "condition" => "md5(`id`) = '$catID' AND deleted = 0"
    ));
    
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }
  
  public function loadModel($id)
  {
    $model = Product::model()->find(array(
      "condition" => "md5(`id`) = '$id' AND deleted = 0 AND enabled = 1"
    ));
    
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }
}